/*
 * @# KryoUtil.java 2011-12-2 下午03:43:25
 * 
 * Copyright (C) 2010 - 2011 广州羿安信息科技有限公司
 * Guangzhou ianswer information technology co. ltd.
 * 
 * All rights reserved!
 */
package com.ianswer.experiments.memcached;

import java.nio.ByteBuffer;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.compress.DeflateCompressor;
import com.esotericsoftware.kryo.serialize.FieldSerializer;

/**
 * @author lunx
 */
public class KryoUtil implements SerializerUtil {

	//本示例测试数据185ms
	
	public byte[] serializer(Object obj) throws RuntimeException {
		Kryo kryo = new Kryo();
		kryo.register(obj.getClass());//DefaultSerializer
		//kryo.register(obj.getClass(), new DeflateCompressor(new FieldSerializer(kryo, obj.getClass())));
		/*kryo.register(obj.getClass(), new Serializer() {
			@Override
			public void writeObjectData(ByteBuffer arg0, Object arg1) {
				
			}
			@Override
			public <T> T readObjectData(ByteBuffer arg0, Class<T> arg1) {
				return null;
			}
		});*/
		ByteBuffer bb = ByteBuffer.allocate(1024);
		kryo.writeObject(bb, obj);
		return bb.array();
	}

	public <T> T unSerializer(byte[] bytes, Class<T> clazz) throws RuntimeException {
		Kryo kryo = new Kryo();
		kryo.register(clazz);
		ByteBuffer bb = ByteBuffer.allocate(1024);
		bb.put(bytes);
		bb.flip();
		return kryo.readObject(bb, clazz);
	}

}
